<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
var bucketSort = function(nums,bucketSize){
    if( nums.length<1 ){
        return nums
    }
    
    let buckets = creatBucekts(nums,bucketSize)
    return nums = sortBuckets(buckets)
}

var creatBucekts = function(nums,bucketSize){
    let max = nums[0]
    let min = nums[0]
    for( var i = 0 ; i<nums.length ; i++ ){
        max = Math.max(max,nums[i])
        min = Math.min(min,nums[i])
    }
    
    let bucketsCount = Math.floor( (max-min) / bucketSize ) + 1
    console.log(bucketsCount)
    let buckets = []
    for( var i = 0 ; i<bucketsCount ; i++ ){
        buckets[i] = []
    }

    for( var i = 0 ; i<nums.length ; i++ ){
        let k = Math.floor( (nums[i]-min) / bucketSize )
        buckets[k].push(nums[i])
        console.log(buckets[k])
    }

    return buckets
}

var sortBuckets = function(buckets){
    let nums = []
    for( var i = 0 ; i<buckets.length ; i++ ){
        if( buckets[i]!=null ){
            maopao(buckets[i])
            nums.push(...buckets[i])
        }
    }
    return nums
}

// 调用一个排序对桶内元素进行排序
var maopao = function (nums){
    for( var i = 0; i<nums.length-1 ;i++ ){
        for(var j = 0; j<nums.length-1-i ; j++ ){
            if(nums[j]>nums[j+1]){
                [nums[j],nums[j+1]]=[nums[j+1],nums[j]]
            }
        }
    }
}

let nums=[3,11,7,2,1,8,9,4,12,5,6,10] //注意观察这两个数组的运行结果，注意适用范围
// let nums=[5,4,3,2,1,4,11,223,455,44,2211,99]
let bucketSize = 4
console.log(bucketSort(nums,bucketSize))
    </script>
</body>
</html>